package cocurrency.lock;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;

/**
 * Created by luzl on 4/7/2017.
 */
public class LockThread extends Thread{
    private static Integer count;
    private String name;
    private ReadWriteLock lock;
    private CyclicBarrier cyclicBarrier;

    public LockThread(ReadWriteLock lock,String name,Integer count,CyclicBarrier cyclicBarrier){
        this.name=name;
        this.lock=lock;
        this.count=count;
        this.cyclicBarrier=cyclicBarrier;

        System.out.println(this.name+" get "+count);
    }

    public void run(){
        try {
            cyclicBarrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
        this.writeCount();
        this.printCount();
    }

    private void printCount(){
        this.lock.readLock().lock();
        //System.out.println(this.name+" "+this.count);
        this.lock.readLock().unlock();
    }

    private void writeCount(){
        this.lock.writeLock().lock();
        this.count=this.count+1;
        System.out.println(this.name+" "+this.count);
        this.lock.writeLock().unlock();

    }
}
